/**
 * 开奖结果的维护
 * context.result - 历史数据
 * context.next - 当期数据
 */

var result = function() {
    var self = this;

    // 当前的游戏名称
    self.currGame = null;

    /**
     * 回调函数
     */
    self.cb = null;
    self.refreshListCb = null;
    self.gotWin = null;

    /**
     * 最近一期所有游戏的开奖结果
     */
    self.lastestOpen = {};

    // 核对下服务器时间
    self.syncTime();
};
result.prototype = {};
result.prototype.construct = result;

/**
 * 切换游戏
 */
result.prototype.switchGame = function(game) {
    var self = this;
    self.currGame = game;
};

/**
 * 最近一期的开奖结果
 */
result.prototype.last = function() {
    var self = this;
    if (!self.currGame) return;
    var r = self.lastestOpen[self.currGame];
    return r;
};

/**
 * 历史开奖记录
 */
result.prototype.list = function() {
    var self = this;
    if (!self.currGame) return [];
    var r = context.result[self.currGame];
    if (isEmpty(r)) return [];
    return r;
};

/**
 * 当前是否处于开奖状态(开奖后的5s处于开奖状态)
 */
result.prototype.isOpen = function() {
    var self = this;
    var c = context.next[self.currGame];
    if (!c) return false;
    var delta = get_server_time() - c.open/1000;
    if (delta < 0) return false;
    if (delta > 5) return false;
    return true;
};

/**
 * 当期的信息，如果没开奖返回封盘和开奖时间，否则返回开奖结果
 */
result.prototype.curr = function() {
    var self = this;
    if (!self.currGame) return;
    var next = context.next[self.currGame];
    if (!next) return;

    if (next.open/1000 - get_server_time() <= 0) {
        // 过了开奖时间，看是否已经开奖啦
        var l = self.last();
        if (l && l.issue == next.issue) return l;
    }
    return next;
};

/**
 * 查看某一期的输赢信息
 */
result.prototype.profit = function(issue, callback) {
    var self = this;
    if (!self.currGame) return;
    CMD.profit(self.currGame, issue, callback);
};

/**
 * 当天盈利
 */
result.prototype.todayProfit = function(callback, fail) {
    var self = this;
    if (!self.currGame) return;
    CMD.find_bet_profit(null, self.currGame, callback, fail);
}

/**
 * 获取开奖结果
 */
result.prototype.pullLastOpen = function() {
    var self = this;

    // 当前选中的游戏，需要已高点的频率抓取
    var f = function() {
        self.refresh_newest();
    };
    Util.registerTimer("RESULT_CURRGAME_LOOP", 5, f);
    f();

    var f2 = function(g) {
        Util.registerTimer("RESULTS_LOOP", 60, function() {
            self.refresh_newest(g);    
        });
        self.refresh_newest(g);
    };
    var f3 = function(g) {
        setTimeout(function() {
            f2(g);
        }, parseInt(i) * 1000);
    }
    for (var i in GameList.menus) {
        if (self.currGame == GameList.menus[i].game) continue;
        f3(GameList.menus[i].game);
    }
}

/**
 * 抓取下一期的信息
 */
result.prototype.pullNext = function() {
    var self = this;
    var f = function() {
        var c = self.curr();
        var c = self.curr();
        if (c && get_server_time() - c.open/1000 >= 2 || c && !c.open) {
            console.log("过了开奖时间，刷新next");
            self.refresh_curr();
        }
    };
    Util.registerTimer("PULL_NEXT_LOOP", 3, f);
    f();
};

// 抓取所有赢的记录
result.prototype.bet_win_query = function() {
    var self = this;
    CMD.query_bet_win(function(r) {
        if (isEmpty(r)) return;

        // 刷新下未结算投注列表
        Lottery.refresh_uncheck();
        if (self.gotWin)
            self.gotWin(r);
    });
}

// 更新历史开奖结果
result.prototype.refresh_list = function(start, end, size) {
    var self = this;
    var type = self.currGame;
    var data = {
        pageNum: 1,
        pageSize: size || 200,
        type: type,
    };
    if (start) data.start = start;
    if (end) data.end = end;
    CMD.lottery_query(data, function(r) {
        if (type != self.currGame) return;
        context.result[type] = r.list;
        if (self.cb) self.cb();
        if (self.refreshListCb) self.refreshListCb();

        // 刷新下未结算投注列表
        if (window.Lottery)
            Lottery.refresh_uncheck();
    });
};

// 更新最近一期的开奖结果
result.prototype.refresh_newest = function(g) {
    var self = this;
    var type = g || window.game;
    
    if (type == window.game) {
        var a = self.last();
        var b = self.curr();
        if (!Util.isEmpty(a) && !Util.isEmpty(b) && 
            parseInt(a.issue) + 1 == parseInt(b.issue)) return;
    }

    var data = {
        pageNum: 1,
        pageSize: 1,
        type: type,
    }
    CMD.lottery_query(data, function(r) {
        if (Util.isEmpty(r.list)) return;
        if (type != self.currGame) {
            self.lastestOpen[type] = r.list[0];
            return;
        }

        var last = self.last();
        if (!last) {
            // 第一次进来
            self.lastestOpen[type] = r.list[0];
            self.refresh_list();
            Lottery.refresh_uncheck();
            if (self.cb) self.cb();
        }
        else if (last.issue != r.list[0].issue) {
            console.log("刷新完整开奖列表。");
            self.lastestOpen[type] = r.list[0];
            Util.playWinMusic();
            self.refresh_list();
            Lottery.refresh_uncheck();
        }
        else {
            // 啥也不用干
        }
    });
};

// 刷新最新一期的数据
result.prototype.refresh_curr = function() {
    var self = this;
    var type = self.currGame;
    CMD.lottery_next(type, function(r) {
        if (type != self.currGame) return;
        console.log("获得下一期信息", r);
        var c = self.curr();
        if (c && c.issue != r.issue) {
            // 进入下一期了，立刻完整刷新下开奖列表
            self.refresh_list();
            Lottery.refresh_uncheck();
        }
        context.next[type] = r;
        if (self.cb) self.cb();
    });
};

// 核对服务器时间
result.prototype.syncTime = function() {
    var self = this;
    CMD.server_time(function(r) {
        context.deltaTime = parseInt(r.timestamp / 1000 - new Date().getTime() / 1000);
        console.log("服务器与本地的时间差", context.deltaTime);
        if (self.cb) self.cb();
    });
};

// 构建个对象
window.Result = new result();
